from PySide6.QtCore import Property,Qt,QObject, Slot, Signal,QAbstractTableModel,QAbstractItemModel
from PySide6.QtQml import  QmlElement
from PySide6.QtWidgets import QFileDialog
from PySide6.QtCore import QTimer
from PySide6 import QtSql,QtCore
from PySide6.QtSql import QSqlDatabase,QSqlQuery,QSqlTableModel
from time import strftime, localtime
import json
import datetime
import logging
import random
import os
import platform
import traceback
from openpyxl import load_workbook
import re
import logging
# To be used on the @QmlElement decorator
# (QML_IMPORT_MINOR_VERSION is optional)
QML_IMPORT_NAME = "QBridge"
QML_IMPORT_MAJOR_VERSION = 1
class SqlContactModel(QtSql.QSqlQueryModel):
    def createTable(self):
        if ("Contacts" in QSqlDatabase.database().tables()):
            return;

        query=QSqlQuery()
        if (not query.exec(
            "CREATE TABLE IF NOT EXISTS 'Contacts' ("
            "   'name' TEXT NOT NULL,"
            "   PRIMARY KEY(name)"
            ")")) :
            logging.info("Failed to query database: %s" % str(query.lastError().text()));

        query.exec("INSERT INTO Contacts VALUES('Albert Einstein')");
        query.exec("INSERT INTO Contacts VALUES('Ernest Hemingway')");
        query.exec("INSERT INTO Contacts VALUES('Hans Gude')");
    def __init__(self,parent):
        super().__init__(parent)
        self.createTable();

        query=QSqlQuery();
        if (not query.exec("SELECT * FROM Contacts")):
            logging.info("Contacts SELECT query failed: %s" % str(query.lastError().text()));

        self.setQuery(query);
        if (self.lastError().isValid()):
            logging.info("Cannot set query on SqlContactModel: %s" % str(self.lastError().text()));
        logging.info(self.rowCount())
    def rowCount(self):
        logging.info("here")
        return super().rowCount()

@QmlElement
class Bridge(QObject):
    updated = Signal(str, arguments=['time'])
    def __init__(self):
        super().__init__()
        # Define timer.
        self.timer = QTimer()
        self.timer.setInterval(1000)  # msecs 100 = 1/10th sec
        self.timer.timeout.connect(self.update_time)
        self.timer.start()
        self.sqlContactModel=SqlContactModel(self)
    @Slot(str,result=QAbstractTableModel)
    def getfilepath(self,filepath):
        self.datafilepath =  filepath
        df = ppdd.readdatafile(filepath)
        self.pandasmodel = PandasModel(df)
        return self.pandasmodel    
    def update_time(self):
        curr_time = strftime("%H:%M:%S", localtime())
        self.updated.emit(curr_time)
if __name__ == '__main__':
    b=Bridge();
    b.getPacks("{}");
